Page({
  data: {
    histories: [],
    showHistories: false,
    showIntro: true,
    isAgree: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    if (!this.data.isAgree) {
      wx.showModal({
        title: '温馨提示',
        content: '请先同意用户协议',
        showCancel: false, // 不显示取消按钮
        confirmText: '知道了',
        success: (res) => {
          if (res.confirm) {
            console.log('用户确认');
          }
        }
      });
    }
  },
  /**
   * 生命周期函数--启动或从后台进入前台时触发
   */
  onShow(options) {
    this.setData({
      histories: [],
      showHistories: false,
      showIntro: true,
    })
    let index = 0;
    let storedMessages = wx.getStorageSync('chatMessages' + index); // 首先先读一个数据

    // 如果第一个数据不为空
    while (storedMessages) {
      this.data.histories.push("历史记录" + index + "：" + storedMessages[0].content); // push拼接
      ++index;
      storedMessages = wx.getStorageSync('chatMessages' + index);
    }
    this.setData({
      histories: this.data.histories,
    })
    getApp().globalData.historiesLength = this.data.histories.length; // 全局变量传递历史记录数组长度
    console.log("Showing before-chat page, this.data.histories = " + this.data.histories)
  },

  viewConversationHistory: function () {
    // const t = this.data.histories;
    // this.data.histories = [];
    this.setData({
      showHistories: !this.data.showHistories,
      showIntro: !this.data.showIntro
    });
  },

  navigateToChat: function () {
    wx.navigateTo({
      url: '/pages/agent/chat/chat?enableSendCard=true',
    })
  },

  navigateToDirect: function () {
    wx.navigateTo({
      url: '/pages/agent/chat/chat?enableSendCard=false',
    })
  },

  goOnHistory: function (event) {
    wx.navigateTo({
      url: '/pages/agent/chat/chat?enableSendCard=false&targetHistoryItem=' + event.currentTarget.id,
    })
  },

  agreeToTerms(e) {
    const checkboxValue = e.detail.value;
    if (checkboxValue.includes('agree')) {
      console.log('用户已同意用户协议');
      this.setData({
        isAgree: true,
      })
    } else {
      console.log('用户取消了同意用户协议');
      this.setData({
        isAgree: false,
      })
    }
  }

});